<template>
    <div class="publish-button">
        <el-button type="primary" class="publish-btn" @click="showDialog = true">发布</el-button>

        <!-- 发布弹窗 -->
        <el-dialog v-model="showDialog" width="800px" :close-on-click-modal="false" :close-on-press-escape="false"
            :before-close="handleDialogClose" style="margin-top: 30px;padding: 10px;">
            <h2>出售农产品信息</h2>
            <br />
            <el-form ref="formRef" :model="productData" :rules="rules" label-width="120px" :validate-trigger="'change'">
                <el-form-item label="农产品名称" prop="product_name">
                    <el-input v-model="productData.product_name" placeholder="请输入产品名称" />
                </el-form-item>

                <el-form-item label="分类" prop="category">
                    <el-select v-model="productData.category" placeholder="请选择分类">
                        <el-option label="水果类" value="水果" />
                        <el-option label="蔬菜类" value="蔬菜" />
                        <el-option label="粮食类" value="粮食" />
                        <el-option label="禽蛋类" value="禽蛋" />
                        <el-option label="乳制品" value="乳制品" />
                    </el-select>
                </el-form-item>

                <el-form-item label="地区" prop="region">
                    <el-input v-model="productData.region" placeholder="请输入地区" />
                </el-form-item>

                <el-form-item label="出售单价(元/斤)" prop="price">
                    <el-input-number v-model="productData.price" :min="0" :precision="2" :step="0.5"
                        style="width: 200px" />
                </el-form-item>

                <el-form-item label="出售总量(斤)" prop="total_stock">
                    <el-input-number v-model="productData.total_stock" :min="0" :precision="2" :step="100"
                        style="width: 200px" />
                </el-form-item>


                <el-form-item label="简介" prop="description">
                    <el-input v-model="productData.description" type="textarea" :rows="3" placeholder="请输入简介" maxlength="35" show-word-limit />
                </el-form-item>

                <el-form-item label="具体描述" prop="introduction">
                    <el-input v-model="productData.introduction" type="textarea" :rows="6" placeholder="请输入具体描述" />
                </el-form-item>
                <el-form-item label="上传图片" prop="images">
                <el-upload
                    v-model="fileList"
                    action="#"
                    list-type="picture-card"
                    :auto-upload="false"
                    :limit="5"
                    :on-exceed="handleExceed"
                    :on-preview="handlePictureCardPreview"
                    :on-remove="handleRemove"
                    :on-change="handleFileChange"
                    accept=".jpg,.jpeg,.png,.gif"
                    multiple
                >
                    <el-icon><Plus /></el-icon>
                    <template #tip>
                        <div class="el-upload__tip">
                            请上传jpg/png/gif格式图片，最多5张，第一张为封面图
                        </div>
                    </template>
                </el-upload>
            </el-form-item>
            
            <!-- 图片预览弹窗 -->
            <el-dialog v-model="previewVisible" title="预览图片" class="preview-dialog" width="64%" style="margin-top: 8vh">
                <img w-full :src="previewImage" alt="Preview Image" class="preview-image" />
            </el-dialog>
            </el-form>

            <template #footer>
                <span class="dialog-footer">
                    <el-button id="pushb" type="primary" @click="send">确认发布</el-button>
                </span>
            </template>
        </el-dialog>
    </div>
</template>

<script setup>
import { ref, reactive } from 'vue';
import { inject } from 'vue';
import { ElMessageBox,ElLoading } from 'element-plus';
import { Plus } from '@element-plus/icons-vue';

import { useMainStore } from '@/stores';
const store = useMainStore();
const $axios = inject('$axios');
const emit = defineEmits(['publish', 'fresh']);
const $tools = inject('$tools')

const showDialog = ref(false);
const formRef = ref(null);
const fileList = ref([]);
const previewVisible = ref(false);
const previewImage = ref('');

// 表单数据
const productData = reactive({
    userId: '',
    product_name: '',
    category: '',
    region: '',
    price: 0,
    total_stock: 0,
    listed_quantity: 0,
    description: '',
    introduction: '',
});


// 表单验证规则
const rules = {
    product_name: [
        { required: true, message: '请输入产品名称', trigger: 'blur' },
        { min: 2, max: 50, message: '长度在 2 到 50 个字符', trigger: 'blur' }
    ],
    category: [
        { required: true, message: '请选择产品分类', trigger: 'change' }
    ],
    region: [
        { required: true, message: '请输入地区', trigger: 'blur' }
    ],
    total_stock: [
        { required: true, message: '请输入总量', trigger: 'blur' },
        { type: 'number', min: 0.01, message: '总量必须大于0', trigger: 'blur' }
    ],
    price: [
        { required: true, message: '请输入价格', trigger: 'blur' },
        { type: 'number', min: 0.01, message: '价格必须大于0', trigger: 'blur' }
    ],
    description: [
        { required: true, message: '请输入简介内容', trigger: 'blur' },
        { min: 10, max: 1000, message: '长度在 10 到 1000 个字符之间', trigger: 'blur' }
    ],
    introduction: [
        { required: true, message: '请输入描述', trigger: 'blur' },
        { min: 10, max: 1000, message: '长度在 10 到 1000 个字符之间', trigger: 'blur' }
    ],
};

// 处理弹窗关闭
const handleDialogClose = (done) => {
    const hasData = productData.product_name || productData.category || productData.region ||
        productData.total_stock > 0 || productData.price > 0 || productData.description;
    if (hasData) {
        ElMessageBox.confirm('确认关闭？输入的内容将会丢失', '', {
            confirmButtonText: '好的',
            cancelButtonText: '取消',
            type: 'warning'
        })
            .then(() => {
                formRef.value?.resetFields();
                formRef.value?.clearValidate();
                showDialog.value = false;
                done && done();
            })
            .catch(() => { });
    } else {
        formRef.value?.resetFields();
        formRef.value?.clearValidate();
        showDialog.value = false;
        done && done();
    }
};
// 允许的图片格式
const allowedImageTypes = ['image/jpeg', 'image/png', 'image/gif'];
// 图片预览处理
const handlePictureCardPreview = (file) => {
    previewImage.value = file.url;
    previewVisible.value = true;
};

// 处理图片移除
const handleRemove = (file, uploadFileList) => {
    console.log(file, uploadFileList);
    fileList.value = uploadFileList;
};

// 处理图片变更
const handleFileChange = (file, uploadFileList) => {
    fileList.value = uploadFileList;
    console.log('文件列表已更新:', fileList.value);
};

// 处理超出限制
const handleExceed = () => {
    ElMessageBox.alert('最多只能上传5张图片', '提示', {
        confirmButtonText: '确定'
    });
};

// 处理发布
const send = () => {
    formRef.value.validate(async (valid) => {
        if (valid) {
            // 发布成功
            if (fileList.value.length === 0) {
                ElMessageBox.alert('至少上传一张图片', '提示', {
                    confirmButtonText: '确定'
                });
                return;
            }
            
            // 检查文件类型
            for (let i = 0; i < fileList.value.length; i++) {
                const file = fileList.value[i].raw;
                if (!allowedImageTypes.includes(file.type)) {
                    ElMessageBox.alert('请上传有效的图片格式（jpg、jpeg、png、gif）', '提示', {
                        confirmButtonText: '确定'
                    });
                    return;
                }
            }

            productData.userId = store.userdata.user_id;
            // console.log(productData);
            productData.listed_quantity = productData.total_stock;

            const formData = new FormData();

            // 遍历所有选中的文件并添加到 formData
            for (let i = 0; i < fileList.value.length; i++) {
                formData.append('images', fileList.value[i].raw);
            }

            // 添加产品数据
            formData.append('productData', JSON.stringify(productData));


            // 显示加载动画
            const loadingInstance = ElLoading.service({
                lock: true,
                text: '正在上传中...',
                background: 'rgba(0, 0, 0, 0.7)'
            });
            
            try {
                // 使用 fetch 发送 POST 请求
                const response = await fetch('http://159.75.133.177:8080/agri_products/adds', {
                    method: 'POST',
                    body: formData,
                    headers: {
                        'Authorization': `${localStorage.getItem('token')}`
                    },
                });
                
                // console.log(response);
                
                // 检查响应状态
                if (response.ok) {
                    $tools.alertMsg('发布成功', 'success');
                    formRef.value?.resetFields();
                    formRef.value?.clearValidate();
                    showDialog.value = false;
                    emit('fresh');
                } else {
                    const errorData = await response.json();
                    $tools.alertMsg(`发布失败: ${errorData.message || '未知错误'}`, 'error');
                }
            } catch (error) {
                console.error('发布过程中出错:', error);
                $tools.alertMsg('发布失败，请稍后重试', 'error');
            } finally {
                // 无论成功失败，都关闭加载动画
                loadingInstance.close();
            }
        } else {
            // 验证失败
            return false;
        }
    });
}
</script>

<style lang="less" scoped>
.publish-button {
    .publish-btn {
        background: #409eff;
    }
}

.el-dialog {
    width: 1100px;
    margin-top: 50px;
}

:deep(.el-dialog) {
    .el-dialog__body {
        padding: 20px 40px;
    }
}

.showImage-el {
    width: 1100px;
    height: 600px;
    display: flex;
    justify-content: center;

    .showImage {
        margin: 0;
        width: 1100px;
        object-fit: contain;
        object-position: center;
    }
}

:deep(.el-upload--picture-card) {
    width: 120px;
    height: 120px;
    line-height: 120px;
}

:deep(.el-upload-list--picture-card .el-upload-list__item) {
    width: 120px;
    height: 120px;
}

.dialog-footer {
    padding-right: 40px;

    #pushb {
        width: 80px;
        margin-bottom: 20px;
    }
}

// 添加预览图片的样式
.preview-dialog {
    :deep(.el-dialog__body) {
        display: flex;
        justify-content: center;
        align-items: center;
        padding: 10px;
        min-height: 300px;
        box-sizing: border-box;
    }
    
    :deep(.el-dialog__header) {
        margin-right: 0;
        text-align: center;
    }
    
    :deep(.el-dialog) {
        display: flex;
        flex-direction: column;
    }
}

.preview-image {
    max-width: 100%;
    max-height: 64vh; // 设置最大高度为视口高度的70%
    object-fit: contain;
    margin: 0 auto;
    display: block;
}
</style>